<?php

namespace app\service;


use app\model\DepartmentModel;
use app\model\TaskModel;
use app\model\TenantUserDepartmentModel;
use app\model\TenantUserModel;
use app\tool\SingletonTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\Collection;
use think\Model;

class DepartmentService
{
    use SingletonTrait;

    /**
     * 查询用户指定角色的部门信息
     * @param $userId
     * @param $tenantId
     * @param array $roleCode
     * @return TenantUserModel|array|mixed|Query|Model|null
     */
    public function getUserDepartmentList($userId, $tenantId, array $roleCode)
    {
        if (empty($userId) || empty($tenantId)) {
            return [];
        }
        $dbr = (new \app\model\TenantUserModel)->cache(5)
            ->field('tenant_user.id,tenant_user.user_id,tenant_user.tenant_id,
            tenant_user_department.department_id,
            tenant_user_role.role_id,tenant_user.status,tenant_user.created,tenant_user.tenant_position_id')
            ->join('tenant_user_role', 'tenant_user_role.tenant_user_id = tenant_user.id', 'LEFT')
            ->join('tenant_user_department', 'tenant_user_department.tenant_user_id = tenant_user.id', 'LEFT')
            ->where('user_id', $userId)
            ->where('tenant_id', $tenantId);
        if (!empty($roleCode)) {
            $dbr
                ->join('role', 'role.id = tenant_user_role.role_id')
                ->whereIn('role.code', $roleCode);
        }
        $list = $dbr->select();
        if (empty($list->toArray())) {
            return [];
        }
        return $list->toArray();
    }

    /**
     * 查询用户部门环节id
     * @param $tenantId
     * @param $userId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserDepartmentStepCategoryIdList($tenantId, $userId): array
    {
        $dbr = TenantUserModel::field('department.*')
            ->join('tenant_user_department', 'tenant_user_department.tenant_user_id = tenant_user.id')
            ->join('department', 'tenant_user_department.department_id = department.id')
            ->where('tenant_user.user_id', $userId)
            ->where('department.tenant_id', $tenantId);
        $departmentList = $dbr->select();
        if (empty($departmentList)) {
            return [];
        }
        $existCheck = [];
        $stepCategoryIds = [];
        foreach ($departmentList as $department) {
            if (empty($department['step_category_ids'])) {
                continue;
            }
            $stepCategoryIdsArr = explode(',', $department['step_category_ids']);
            foreach ($stepCategoryIdsArr as $s) {
                if (empty($s)) {
                    continue;
                }
                if (!empty($existCheck[$s])) {
                    continue;
                }
                $existCheck[$s] = true;
                $stepCategoryIds[] = $s;
            }
        }
        return $stepCategoryIds;
    }

    /**
     * 查询部门信息
     * @param $tenantId
     * @param $where
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getDepartmentList($tenantId, $where): array
    {
        $query = (new \app\model\DepartmentModel)->field('*');
        if (!empty($tenantId)) {
            $query->where('tenant_id', $tenantId);
        }
        if (!empty($where)) {
            $query->whereRaw($where);
        }
        $list = $query->select();
        // 通过租户ID获取部门列表
        if (empty($list->toArray())) {
            return [];
        }
        return $list->toArray();
    }

    /**
     * @param array $where
     * @return array|Collection|\think\model\Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getDepartment(array $where = [])
    {
        return DepartmentModel::where($where)->select();
    }


    /**
     * 获取部门/环节下所有用户ID (支持独立筛选)
     * @param int|array $departmentId 仅环节: 0 或 []
     * @param int|array $todoStepCategoryId
     * @param int $tenantId
     * @param string $filterType ['any','all']
     * @return array
     */
    public function getDepartmentUserIdList($departmentId = 0, $todoStepCategoryId = [], int $tenantId = 0, string $filterType = 'any'): array
    {
        if (empty($departmentId) && empty($todoStepCategoryId)) {
            return [];
        }
        $dbr = TenantUserModel::join('user', 'user.union_id = tenant_user.user_id')
            ->join('tenant_user_department', 'tenant_user_department.tenant_user_id = tenant_user.id');
        if (!empty($departmentId)) {
            if (!is_array($departmentId)) {
                $departmentId = [$departmentId];
            }
            $dbr = $dbr->whereIn('tenant_user_department.department_id', $departmentId);
        }
        if (!empty($todoStepCategoryId)) {
            if (!is_array($todoStepCategoryId)) {
                $todoStepCategoryId = [$todoStepCategoryId];
            }
            $dbr = $dbr->join('department', 'department.id = tenant_user_department.department_id')
                ->where('tenant_user.tenant_id', $tenantId);
            switch ($filterType) {
                case 'any':
                    $dbr = $dbr->whereFieldRaw("array_length(array_intersect(split(department.step_category_ids, ','), [" . implode(',', $todoStepCategoryId) . "]))", '>', 0);
                    break;
            }
        }
        return $dbr->column('distinct user.id');
    }

    /**
     * 查询用户部门信息
     * @param integer $tenantId
     * @param integer $userId
     * @param array $roleCodeList
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserDepartmentListInfo(int $userId, int $tenantId, array $roleCodeList): array
    {
        $departmentIdJoin = TenantUserModel::
        join('tenant_user_role', 'tenant_user_role.tenant_user_id = tenant_user.id')
            ->join('role', 'role.id = tenant_user_role.role_id')
            ->join('tenant_user_department', 'tenant_user_department.tenant_user_id = tenant_user.id')
            ->where([
                'tenant_user.tenant_id' => $tenantId,
                'tenant_user.user_id' => $userId,
            ])
            ->whereIn('role.code', $roleCodeList)
            ->field('tenant_user_department.department_id')
            ->buildSql();
        return DepartmentModel::whereRaw("id in (" . $departmentIdJoin . ")")->select()->toArray();
    }

    /**
     * 校验部门是否可删除
     * @param $param [department_id_list => [部门id]]
     * @return array [部门id => true:可删除 | false:不可删除]
     */
    public function deleteCheck($param): array
    {
        $tenantUserDepartmentList = TenantUserDepartmentModel::where('department_id', 'IN', $param['department_id_list'])
            ->field(['department_id'])
            ->group('department_id')
            ->column('department_id');

        if(empty($tenantUserDepartmentList)){
            return [];
        }

        $taskDepartmentList = TaskModel::where('department_id', 'IN', $param['department_id_list'])
            ->field(['department_id'])
            ->group('department_id')
            ->column('department_id');
        if(empty($taskDepartmentList)){
            return [];
        }

        $res = [];
        foreach ($param['department_id_list'] as $departmentId) {
            $res[$departmentId] = true;
            // 有用户不能删除
            if (in_array($departmentId, $tenantUserDepartmentList)) {
                $res[$departmentId] = false;
            }

            // 有任务不能删除
            if (in_array($departmentId, $taskDepartmentList)) {
                $res[$departmentId] = false;
            }
        }

        return $res;
    }
}
